<template>
  <div class="scenic-collec-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>
            <i class="icon-star">⭐</i>
            我的景点收藏
          </h2>
          <div class="header-subtitle">收藏精彩的旅行景点</div>
        </div>
        <div class="total-count">
          <span class="count-number">{{ filteredScenics.length }}</span>
          <span class="count-text">个收藏</span>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <div class="search-bar">
        <i class="search-icon">🔍</i>
        <input
          v-model="searchText"
          @input="handleSearch"
          placeholder="搜索景点名称、省份或城市"
          class="search-input"
        />
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载精彩内容中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredScenics.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="icon-empty">💭</i>
      </div>
      <h3 class="empty-title">还没有收藏的景点</h3>
      <p class="empty-description">快去发现那些精彩的旅行景点吧！</p>
      <router-link to="/homepage/scenic" class="explore-btn">
        <i class="icon-explore">🔍</i>
        探索景点
      </router-link>
    </div>

    <!-- 景点列表 -->
    <div v-else class="scenic-list">
      <div v-for="scenic in filteredScenics" :key="scenic.collectId" class="scenic-card">
        <!-- 图片轮播区域 -->
        <div class="scenic-img-carousel" @click="viewDetail(scenic)">
          <img
            :src="scenic.images[scenic.currentImg] || defaultImg"
            class="scenic-img"
            alt="景点图片"
          />
          <div class="image-overlay"></div>
          <div class="carousel-controls" v-if="scenic.images.length > 1">
            <span
              class="carousel-arrow"
              @click.stop="prevImg(scenic)"
              :class="{ disabled: scenic.currentImg === 0 }"
            >&#8592;</span>
            <span
              class="carousel-arrow"
              @click.stop="nextImg(scenic)"
              :class="{ disabled: scenic.currentImg === scenic.images.length - 1 }"
            >&#8594;</span>
          </div>
          <div class="collect-badge">
            <i class="badge-icon">⭐</i>
          </div>
        </div>
        
        <!-- 内容区域 -->
        <div class="scenic-content">
          <h3 class="scenic-title">{{ scenic.name }}</h3>
          <div class="scenic-meta">
            <div class="meta-item">
              <i class="meta-icon">📍</i>
              <span>{{ scenic.province }}{{ scenic.city }}</span>
            </div>
            <div class="meta-item">
              <i class="meta-icon">⛰️</i>
              <span>海拔 {{ scenic.altitude || '未知' }} 米</span>
            </div>
            <div class="meta-item">
              <i class="meta-icon">📅</i>
              <span>{{ scenic.favoriteTime }}</span>
            </div>
          </div>
        </div>

        <!-- 底部操作区 -->
        <div class="scenic-footer">
          <!-- 难度评级 -->
          <div class="difficulty-rating">
            <span class="difficulty-text">难度:</span>
            <div class="stars">
              <span v-for="i in 5" :key="i" class="star" :class="{ active: i <= getDifficultyLevel(scenic.difficulty) }">★</span>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="scenic-actions">
            <button class="collect-btn active" @click.stop="toggleCollect(scenic)">
              <i class="collect-icon">⭐</i>
              <span>取消收藏</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: "ScenicCollec",
  data() {
    return {
      searchText: "",
      scenics: [],
      loading: true,
      defaultImg: "https://img1.baidu.com/it/u=2331851122,2068186006&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333"
    };
  },
  computed: {
    filteredScenics() {
      if (!this.searchText) return this.scenics;
      const text = this.searchText.trim().toLowerCase();
      return this.scenics.filter(
        s =>
          (s.name && s.name.toLowerCase().includes(text)) ||
          (s.province && s.province.toLowerCase().includes(text)) ||
          (s.city && s.city.toLowerCase().includes(text))
      );
    }
  },
  async mounted() {
    await this.fetchScenicCollects();
    this.loading = false;
  },
  methods: {
    getDifficultyLevel(difficulty) {
      if (!difficulty) return 0;
      const num = parseFloat(difficulty);
      if (isNaN(num)) return 0;
      return Math.min(5, Math.max(1, Math.round(num)));
    },
    async fetchScenicCollects() {
      try {
        this.loading = true;
        // 1. 获取当前用户userId
        const loginId = localStorage.getItem('loginId');
        const token = localStorage.getItem('token');
        if (!loginId) {
          this.scenics = [];
          return;
        }
        
        const userRes = await fetch(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
        const userData = await userRes.json();
        const userId = userData.userId;
        
        if (!userId) {
          this.scenics = [];
          return;
        }
        
        // 2. 获取该用户的收藏列表
        const res = await fetch(`http://localhost:8080/sf/listByUser?userId=${userId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Cache-Control': 'no-cache'
          }
        });
        const data = await res.json();
        
        const scenicList = [];
        for (const item of data || []) {
          // 获取景点详细信息
          let scenicDetail = {};
          try {
            const detailRes = await fetch(`http://localhost:8080/mw/ScenicSpotById?id=${item.scenicSpotId}`);
            scenicDetail = await detailRes.json();
          } catch (e) {}
          
          // 获取景点图片
          let images = [];
          try {
            const imgRes = await fetch(`http://localhost:8080/api/scenicSpotImage?scenicSpotId=${item.scenicSpotId}`);
            images = await imgRes.json();
          } catch (e) {}
          
          // 获取省份城市
          let province = "", city = "";
          try {
            let regionId = scenicDetail.regionId || scenicDetail.regionID;
            if (regionId) {
              const regionRes = await fetch(`http://localhost:8080/api/regions/${regionId}`);
              const region = await regionRes.json();
              province = region.province || "";
              city = region.city || "";
            }
          } catch (e) {}
          
          // 格式化收藏时间
          let favoriteTime = item.favoriteTime;
          if (favoriteTime && typeof favoriteTime === "string") {
            favoriteTime = favoriteTime.slice(0, 10);
          }
          
          scenicList.push({
            collectId: item.scenicFavoriteId,
            id: item.scenicSpotId,
            name: item.scenicAreaName || scenicDetail.scenicAreaName || "未命名景点",
            altitude: scenicDetail.altitude || "未知",
            difficulty: scenicDetail.comprehensiveDifficultyIndex || "0",
            province,
            city,
            favoriteTime,
            images: images.length ? images : [this.defaultImg],
            currentImg: 0,
            collected: true
          });
        }
        this.scenics = scenicList;
      } catch (error) {
        console.error('获取收藏景点失败:', error);
        ElMessage.error('获取收藏景点失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      // 搜索功能由computed属性filteredScenics自动处理
    },
    prevImg(scenic) {
      if (scenic.currentImg > 0) scenic.currentImg--;
    },
    nextImg(scenic) {
      if (scenic.currentImg < scenic.images.length - 1) scenic.currentImg++;
    },
    viewDetail(scenic) {
      this.$router.push({ name: "ScenicDetail", params: { id: scenic.id } });
    },
    async toggleCollect(scenic) {
      if (!scenic.collected) return;
      
      try {
        const token = localStorage.getItem('token');
        const deleteRes = await fetch(`http://localhost:8080/sf/delete/${scenic.collectId}`, {
          method: "DELETE",
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (!deleteRes.ok) {
          const errorText = await deleteRes.text();
          console.error('删除请求失败:', errorText);
          try {
            const errorData = JSON.parse(errorText);
            ElMessage.error(`取消收藏失败: ${errorData.message || '未知错误'}`);
          } catch (parseError) {
            ElMessage.error(`取消收藏失败: ${errorText}`);
          }
          return;
        }
        
        ElMessage.success('取消收藏成功');
        this.scenics = this.scenics.filter(s => s.collectId !== scenic.collectId);
      } catch (error) {
        console.error('取消收藏失败:', error);
        ElMessage.error('取消收藏失败，请稍后重试');
      }
    }
  }
};
</script>

<style scoped>
.scenic-collec-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 24px;
}

.header-content {
  background: white;
  padding: 24px 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-star {
  font-size: 24px;
  animation: twinkle 2s infinite;
}

@keyframes twinkle {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.6; }
}

.header-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.total-count {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #a6a6e4 0%, #c3aadd 100%);
  color: white;
  padding: 16px 20px;
  border-radius: 12px;
  min-width: 80px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.count-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 搜索栏 */
.search-container {
  margin-bottom: 24px;
  background: white;
  padding: 16px 24px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.search-bar {
  position: relative;
  max-width: 500px;
  margin: 0 auto;
}

.search-icon {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 18px;
  color: #7f8c8d;
}

.search-input {
  width: 100%;
  padding: 12px 20px 12px 48px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s;
  background: #f8fafc;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
  background: white;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.explore-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

/* 景点列表 */
.scenic-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
}

.scenic-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
}

.scenic-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.scenic-img-carousel {
  position: relative;
  height: 200px;
  overflow: hidden;
  cursor: pointer;
}

.scenic-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.scenic-card:hover .scenic-img {
  transform: scale(1.1);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.3) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.scenic-card:hover .image-overlay {
  opacity: 1;
}

.carousel-controls {
  position: absolute;
  bottom: 12px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.carousel-arrow {
  font-size: 20px;
  color: white;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;
  background: rgba(0, 0, 0, 0.4);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
}

.carousel-arrow:hover {
  background: rgba(0, 0, 0, 0.6);
}

.carousel-arrow.disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.collect-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #f7b500;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.badge-icon {
  font-size: 12px;
  animation: twinkle 1.5s ease-in-out infinite;
}

.scenic-content {
  padding: 20px;
  flex: 1;
}

.scenic-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.scenic-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #6b7280;
}

.meta-icon {
  font-size: 16px;
}

.scenic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.difficulty-rating {
  display: flex;
  align-items: center;
  gap: 8px;
}

.difficulty-text {
  font-size: 14px;
  color: #6b7280;
}

.stars {
  display: flex;
  gap: 2px;
}

.star {
  color: #e2e8f0;
  font-size: 16px;
}

.star.active {
  color: #f7b500;
}

.scenic-actions {
  display: flex;
  gap: 8px;
}

.collect-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #ffd700 0%, #f7b500 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(247, 181, 0, 0.3);
}

.collect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(247, 181, 0, 0.5);
}

.collect-btn.active {
  background: linear-gradient(135deg, #e67e22 0%, #d35400 100%);
}

.collect-icon {
  font-size: 14px;
  animation: like-pulse 0.6s ease-in-out;
}

@keyframes like-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.3); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scenic-collec-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .scenic-list {
    grid-template-columns: 1fr;
  }
  
  .scenic-footer {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 20px;
  }
  
  .header-left h2 {
    font-size: 24px;
  }
  
  .scenic-content {
    padding: 16px;
  }
}
</style>